﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ManYor.Phone.Common;
using System.Diagnostics;
using System.Windows.Controls.Primitives;

namespace ManYor
{
    public partial class SliderShowPivot : PhoneApplicationPage
    {
        private PivotItem currentPivotItem;
        private Popup pop;
        private TextBlock pageTb;
        /// <summary>
        /// 构造函数
        /// </summary>
        public SliderShowPivot()
        {
            InitializeComponent();
            InitializePopupPageNumber();
            this.Loaded += new RoutedEventHandler(SliderShowPivot_Loaded);            
        }

        /// <summary>
        /// 初始化页码
        /// </summary>
        private void InitializePopupPageNumber()
        {
            pop = new Popup();
            pop.HorizontalOffset = 0;
            pop.VerticalOffset = 745;

            StackPanel panel1 = new StackPanel();
            panel1.Background = new SolidColorBrush(Colors.Transparent);
            pageTb = new TextBlock();
            pageTb.Text = "10/21";
            pageTb.Foreground = new SolidColorBrush(Colors.White);
            pageTb.FontSize = 25;
            pageTb.Margin = new Thickness(5.0);
            panel1.Children.Add(pageTb);
            pop.Child = panel1;
        }
        /// <summary>
        /// 获取或设置当前页码文本
        /// </summary>
        private string PageNumber
        {
            get { return pageTb.Text; }
            set { pageTb.Text = value; }
        }
        /// <summary>
        /// 页面加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SliderShowPivot_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.IsVisible = false;
            string[] arr = new string[] { "Images/sample.jpg", "Images/sample2.jpg", "Images/sample3.jpg", "Images/sample4.jpg",
                                            "Images/sample5.jpg","Images/sample6.jpg"};
            this.LockedPivot.ItemsSource = arr;
            this.LockedPivot.SelectionChanged += new SelectionChangedEventHandler(pivt_SelectionChanged);            
            this.LockedPivot.LoadedPivotItem += new EventHandler<PivotItemEventArgs>(pivt_LoadedPivotItem);
            this.LockedPivot.UnloadedPivotItem += new EventHandler<PivotItemEventArgs>(LockedPivot_UnloadedPivotItem);

            this.LockedPivot.Loaded += new RoutedEventHandler(LockedPivot_Loaded);
            this.ApplicationBar.IsVisible = false;
            pop.IsOpen = false;

           
        }

        void LockedPivot_Loaded(object sender, RoutedEventArgs e)
        {
            var o = this.LockedPivot.SelectedItem;
        }
      
        /// <summary>
        /// PiovtItem卸载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void LockedPivot_UnloadedPivotItem(object sender, PivotItemEventArgs e)
        {
            LoadOrOnLoadImagePinch(e,false);
            //Debug.WriteLine(counter++ + "LockedPivot_UnloadedPivotItem");
        }

        /// <summary>
        /// 加载或卸载图片的缩放事件
        /// </summary>
        /// <param name="e"></param>
        /// <param name="?"></param>
        private void LoadOrOnLoadImagePinch(PivotItemEventArgs e,bool flag)
        {
            currentPivotItem = e.Item;
            var ls = Common.FindAllChildOfType<Image>(e.Item);
            Image img = ls.Where<Image>(o => o.Name.Equals("ctl_ImgZoom")).FirstOrDefault();
            if (img != null)
            {
                ImgZoom = img;
                var gs = GestureService.GetGestureListener(img);

                if (!flag)
                {
                    gs.PinchStarted -= new EventHandler<PinchStartedGestureEventArgs>(OnPinchStarted);
                    gs.PinchDelta -= new EventHandler<PinchGestureEventArgs>(OnPinchDelta);
                    gs.DragDelta -= new EventHandler<DragDeltaGestureEventArgs>(OnDragDelta);
                    gs.Tap -= new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnTap);
                    gs.DoubleTap -= new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnDoubleTap);
                }
                else
                {
                    gs.PinchStarted += new EventHandler<PinchStartedGestureEventArgs>(OnPinchStarted);
                    gs.PinchDelta += new EventHandler<PinchGestureEventArgs>(OnPinchDelta);
                    gs.DragDelta += new EventHandler<DragDeltaGestureEventArgs>(OnDragDelta);
                    gs.Tap += new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnTap);
                    gs.DoubleTap += new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnDoubleTap);
                }
            }
        }
        /// <summary>
        /// PiovtItem载入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pivt_LoadedPivotItem(object sender, PivotItemEventArgs e)
        {
            LoadOrOnLoadImagePinch(e, true);
        }

        //int counter = 0;
        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            //Debug.WriteLine(counter++ +"_BEGIN:"+this.ApplicationBar.IsVisible);
            this.ApplicationBar.IsVisible = !this.ApplicationBar.IsVisible;            
            //Debug.WriteLine(counter++ + "_END:" + this.ApplicationBar.IsVisible);
            //Debug.WriteLine("-------");
            
        }
        /// <summary>
        /// PiovtItem切换事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pivt_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {           
            this.ApplicationBar.IsVisible = false;
           // pop.IsOpen = false;
        }
        #region Const Variable
        // these two fields fully define the zoom state:
        private double TotalImageScale = 1d;
        private Point ImagePosition = new Point(0, 0);
        private const double MAX_IMAGE_ZOOM = 2;

        private Point _oldFinger1;
        private Point _oldFinger2;
        private double _oldScaleFactor;
        private Image ImgZoom;
        #endregion

        #region Event handlers

        /// <summary>
        /// Initializes the zooming operation
        /// </summary>
        private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
        {
            _oldFinger1 = e.GetPosition(ImgZoom, 0);
            _oldFinger2 = e.GetPosition(ImgZoom, 1);
            _oldScaleFactor = 1;
        }

        /// <summary>
        /// Computes the scaling and translation to correctly zoom around your fingers.
        /// </summary>
        private void OnPinchDelta(object sender, PinchGestureEventArgs e)
        {
            var scaleFactor = e.DistanceRatio / _oldScaleFactor;
            if (!IsScaleValid(scaleFactor))
                return;

            var currentFinger1 = e.GetPosition(ImgZoom, 0);
            var currentFinger2 = e.GetPosition(ImgZoom, 1);

            var translationDelta = GetTranslationDelta(
                currentFinger1,
                currentFinger2,
                _oldFinger1,
                _oldFinger2,
                ImagePosition,
                scaleFactor);

            _oldFinger1 = currentFinger1;
            _oldFinger2 = currentFinger2;
            _oldScaleFactor = e.DistanceRatio;

            UpdateImageScale(scaleFactor);
            UpdateImagePosition(translationDelta);

            if (TotalImageScale > 1.1F)
            {
                //LockablePivot lkPi= this.FindName("LockedPivot") as LockablePivot;
                //lkPi.IsLocked = true;
                e.Handled = true;
            }
            else
            {
                LockablePivot lkPi = this.FindName("LockedPivot") as LockablePivot;
                lkPi.IsLocked = false;
            }
            
        }

        /// <summary>
        /// Moves the image around following your finger.
        /// </summary>
        private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            var translationDelta = new Point(e.HorizontalChange, e.VerticalChange);

            if (IsDragValid(1, translationDelta))
                UpdateImagePosition(translationDelta);
        }

        /// <summary>
        /// Resets the image scaling and position
        /// </summary>
        private void OnDoubleTap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            ResetImagePosition();
        }

        #endregion

        #region Utils

        /// <summary>
        /// Computes the translation needed to keep the image centered between your fingers.
        /// </summary>
        private Point GetTranslationDelta(
            Point currentFinger1, Point currentFinger2,
            Point oldFinger1, Point oldFinger2,
            Point currentPosition, double scaleFactor)
        {
            var newPos1 = new Point(
             currentFinger1.X + (currentPosition.X - oldFinger1.X) * scaleFactor,
             currentFinger1.Y + (currentPosition.Y - oldFinger1.Y) * scaleFactor);

            var newPos2 = new Point(
             currentFinger2.X + (currentPosition.X - oldFinger2.X) * scaleFactor,
             currentFinger2.Y + (currentPosition.Y - oldFinger2.Y) * scaleFactor);

            var newPos = new Point(
                (newPos1.X + newPos2.X) / 2,
                (newPos1.Y + newPos2.Y) / 2);

            return new Point(
                newPos.X - currentPosition.X,
                newPos.Y - currentPosition.Y);
        }

        /// <summary>
        /// Updates the scaling factor by multiplying the delta.
        /// </summary>
        private void UpdateImageScale(double scaleFactor)
        {
            TotalImageScale *= scaleFactor;
            ApplyScale();
        }

        /// <summary>
        /// Applies the computed scale to the image control.
        /// </summary>
        private void ApplyScale()
        {
            ((CompositeTransform)ImgZoom.RenderTransform).ScaleX = TotalImageScale;
            ((CompositeTransform)ImgZoom.RenderTransform).ScaleY = TotalImageScale;
        }

        /// <summary>
        /// Updates the image position by applying the delta.
        /// Checks that the image does not leave empty space around its edges.
        /// </summary>
        private void UpdateImagePosition(Point delta)
        {
            var newPosition = new Point(ImagePosition.X + delta.X, ImagePosition.Y + delta.Y);

            if (newPosition.X > 0) newPosition.X = 0;
            if (newPosition.Y > 0) newPosition.Y = 0;

            if ((ImgZoom.ActualWidth * TotalImageScale) + newPosition.X < ImgZoom.ActualWidth)
                newPosition.X = ImgZoom.ActualWidth - (ImgZoom.ActualWidth * TotalImageScale);

            if ((ImgZoom.ActualHeight * TotalImageScale) + newPosition.Y < ImgZoom.ActualHeight)
                newPosition.Y = ImgZoom.ActualHeight - (ImgZoom.ActualHeight * TotalImageScale);

            ImagePosition = newPosition;

            ApplyPosition();
        }

        /// <summary>
        /// Applies the computed position to the image control.
        /// </summary>
        private void ApplyPosition()
        {
            ((CompositeTransform)ImgZoom.RenderTransform).TranslateX = ImagePosition.X;
            ((CompositeTransform)ImgZoom.RenderTransform).TranslateY = ImagePosition.Y;
        }

        /// <summary>
        /// Resets the zoom to its original scale and position
        /// </summary>
        private void ResetImagePosition()
        {
            TotalImageScale = 1;
            ImagePosition = new Point(0, 0);
            ApplyScale();
            ApplyPosition();
        }

        /// <summary>
        /// Checks that dragging by the given amount won't result in empty space around the image
        /// </summary>
        private bool IsDragValid(double scaleDelta, Point translateDelta)
        {
            if (ImagePosition.X + translateDelta.X > 0 || ImagePosition.Y + translateDelta.Y > 0)
                return false;

            if ((ImgZoom.ActualWidth * TotalImageScale * scaleDelta) + (ImagePosition.X + translateDelta.X) < ImgZoom.ActualWidth)
                return false;

            if ((ImgZoom.ActualHeight * TotalImageScale * scaleDelta) + (ImagePosition.Y + translateDelta.Y) < ImgZoom.ActualHeight)
                return false;

            return true;
        }

        /// <summary>
        /// Tells if the scaling is inside the desired range
        /// </summary>
        private bool IsScaleValid(double scaleDelta)
        {
            return (TotalImageScale * scaleDelta >= 1) && (TotalImageScale * scaleDelta <= MAX_IMAGE_ZOOM);
        }

        #endregion

        private void BottomBar_StateChanged(object sender, ApplicationBarStateChangedEventArgs e)
        {
            pop.IsOpen = this.ApplicationBar.IsVisible;
        }

      
    }
}